# Copyright 2021 The TensorStore Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

load("@bazel_skylib//rules:common_settings.bzl", "BuildSettingInfo")

# TODO: Consider using the bazel --stamp flag:
#
# https://bazel.build/docs/user-manual#workspace-status-command
#  --workspace_status_command program would generate key value pairs,
#  which are stored in https://bazel.build/rules/lib/builtins/ctx#version_file
#
# Also consider exposing the version as a python __version__.py file.

_TEMPLATE = """
// version is auto-generated by tensorstore build.

#ifndef TENSORSTORE_VERSION
#define TENSORSTORE_VERSION "{version}"
#endif  // TENSORSTORE_VERSION

"""

def _tag_release_impl(ctx):
    ctx.actions.write(
        output = ctx.outputs.out,
        content = _TEMPLATE.format(version = ctx.attr.label[BuildSettingInfo].value),
        is_executable = False,
    )
    return [DefaultInfo(files = depset([ctx.outputs.out]))]

tag_release = rule(
    implementation = _tag_release_impl,
    output_to_genfiles = True,
    attrs = {
        "out": attr.output(mandatory = True, doc = "The output file to write the version to."),
        "label": attr.label(mandatory = True, doc = "The label to tag the release with."),
    },
)
